﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BasicCMS.Data
{
    public class ExecuteBuilder : IPersistentBuilder
    {
        private readonly IUnitOfWork unitOfWork;
        private IList<KeyValuePair<string, object>> parameters = new List<KeyValuePair<string, object>>();
        private string sql;
        private IDbCommand command;

        public ExecuteBuilder(IUnitOfWork unitOfWork,string sql)
        {
            this.unitOfWork = unitOfWork;
            this.sql = sql;
        }

        public ExecuteBuilder Param(string name, object value)
        {
            parameters.Add(new KeyValuePair<string, object>(name, value));
            return this;
        }

        public void Persistent()
        {
            foreach (var param in parameters)
            {
                command.Parameters.Add(new SqlParameter("@" + param.Key, param.Value));
            }

            command.CommandText = sql;
            command.ExecuteNonQuery();
        }

        public IDbCommand Command
        {
            set { command = value; }
        }

        public bool IsValid
        {
            get { return !String.IsNullOrEmpty(sql); }
        }
    }
}
